var chargingRecord = [];
var socStatusChart;
var countData = [];
var chargingChart = undefined;
var outputVoltageData = [];
var outputElectricData = [];
var currentSOCData = [];
var research = true;
var exportFlag = undefined;

//查询
$(document).ready(function() {
	showLoading();
	$('title', parent.document).html($('title').text());
	setBaseUrl();
	addTitle("chargingRecordDetails");
	initSocStatusChart();
	search();
});

function search(){
	$('#ID').val($("#detailID", parent.document).val());
	$ajax('searchChargingRecordDetail', 'searchChargingRecordDetail', searchChargingRecordDetail);
	$("#detailID", parent.document).val("");
	$("#histogram").empty();
	chargingChart = echarts.init(document.getElementById('histogram'));
}
function initSocStatusChart(){
	socStatusChart = echarts.init(document.getElementById('stationEcharts'));
	socStatusChart.setOption(setPieStatus("统计信息", [{value: 0, name: "0", "itemStyle": echartStyle('#EAEAEA', false, false, '#EAEAEA')}], ['75%', '80%'], "结束SOC", "0%", "{d}%"));
}
function searchChargingRecordDetail(data) {
	chargingRecord = data && data.chargingRecordList || [];
	createDetailUlBody("detailOneBody", chargingRecordDetailTable, chargingRecord[0], 1);
	createDetailUlBody("detailTwoBody", chargingRecordDetailTable, chargingRecord[0], 2);
	createDetailUlBody("detailThreeBody", chargingRecordDetailTable, chargingRecord[0], 3);
	createDetailUlBody("detailFourBody", chargingRecordDetailTable, chargingRecord[0], 4);
	$("#stationName").html('');
	$("#stationName").html(chargingRecord[0] && (chargingRecord[0].chargingStationName + ' ' +  chargingRecord[0].equipmentName) || '充电站信息获取失败');
	if (chargingRecord[0] && chargingRecord[0].message) {
		$("#chargingMessage").html('<span onclick="seeMessage()" class="bacHoverGreen details operationWord">查看</span>');
	} else {
		$("#chargingMessage").html('-');
	}
	if (!(chargingRecord[0] && chargingRecord[0].carFile)) {
		$('#carFile').html('<img src="static/images/uploadFileBms.png" style="width:30px;height:30px;" />' + '上传');
		$("#carFile").attr("onclick",'importFile("car");return false;');
	} else {
		$('#carFile').html('<img src="static/images/downloadFileBms.png" style="width:30px;height:30px;" />' + formatFileSize(chargingRecord[0].carFileSize));
		$("#carFile").attr("onclick",'exportFile("car");return false;');
	}
	if (!(chargingRecord[0] && chargingRecord[0].chargingProcessFile)) {
		$('#chargingProcessFile').html('<img src="static/images/uploadFileCcs.png" style="width:30px;height:30px;" />' + '上传');
		$("#chargingProcessFile").attr("onclick",'importFile("equipment");return false;');
	} else {
		$('#chargingProcessFile').html('<img src="static/images/downloadFileCcs.png" style="width:30px;height:30px;" />' + formatFileSize(chargingRecord[0].chargingProcessFileSize));
		$("#chargingProcessFile").attr("onclick",'exportFile("equipment");return false;');
	}
	countData = [];
	countData.push({"value": chargingRecord[0] && chargingRecord[0].startSOC || 0, 
		"name": chargingRecord[0] && chargingRecord[0].startSOC || 0, 
		"itemStyle": echartStyle('#419AF1', false, false, '#419AF1')
		});
	countData.push({"value": chargingRecord[0] && chargingRecord[0].totalSOC || 0, 
		"name": chargingRecord[0] && chargingRecord[0].totalSOC || 0,  
		"itemStyle": echartStyle('#09BE09', false, false, '#09BE09')
		});
	countData.push({"value": chargingRecord[0] && (100 - (chargingRecord[0].totalSOC+chargingRecord[0].startSOC)) || 0, 
		"name":chargingRecord[0] && (100 - (chargingRecord[0].totalSOC+chargingRecord[0].startSOC)) || 0,
		"itemStyle": echartStyle('#EAEAEA', false, false, '#EAEAEA')
		});
	option.series[0].data = countData;
	option.title.text = (chargingRecord[0].endSOC || 0) + "%";
	socStatusChart.setOption(option, true);
	$("#stationEcharts")[0].children[0].style.margin="auto";
	$("#stationEcharts")[0].children[0].style.width = $("#stationEcharts").width();
	$("#startSOC").html(chargingRecord[0].startSOC || 0);
	$("#totalSOC").html(chargingRecord[0].totalSOC);
	$("#carNumber").html('<a class="details" onclick=\'pass("'+chargingRecord[0].carNumber+'")\'>'+chargingRecord[0].carNumber+'</a>');
	$("#chargingStationName").html('<a class="details" onclick=\'chargingStationName("0")\'>'+chargingRecord[0].chargingStationName+'</a>');
	var startChargingTime = chargingRecord[0].startChargingDTTM;
	var endChargingDTTM = chargingRecord[0].endChargingDTTM;
	chargingChart.showLoading({text : "曲线加载中..."});
	$ajax('chargingChartHistory', 
		  {EquipmentNo: $("#equipmentNo", parent.document).val(), 
		   CardNo: chargingRecord[0].cardNo,
		   CarNumber: chargingRecord[0].carNumber,
		   StartChargingTime: timeStamp2String(chargingRecord[0].startChargingDTTM),
		   EndChargingTime: timeStamp2String(chargingRecord[0].endChargingDTTM)
		  }, 
		 searchChargingStatus, '', searchChargingStatus);
	
	setTimeout(hideLoading, 500);
}
function searchChargingStatus(data){
	setTimeout(function (){chargingChart.hideLoading();}, 200);
	if(data && data.outputVoltage && data.outputVoltage.length > 0){
		outputVoltageData = data.outputVoltage || [];
		outputElectricData = data.outputElectric || [];
		currentSOCData = data.currentSOC || [];
	} else {
		if (research) {
			research = false;
			chargingChart.showLoading({text : "数据深度查询，曲线加载中..."});
			$ajax('chargingChartHistory', 
				  {EquipmentNo: $("#equipmentNo", parent.document).val(), 
				   CardNo: chargingRecord[0].cardNo,
				   CarNumber: chargingRecord[0].carNumber,
				   StartChargingDate: timeStamp2String(chargingRecord[0].startChargingDTTM),
				   EndChargingDate: timeStamp2String(chargingRecord[0].endChargingDTTM)
				  }, 
				  searchChargingStatus, '', searchChargingStatus);
		}
	}
	changeEchart();
}
function seeMessage(){
	if (chargingRecord[0].message){
		$("#message").val(chargingRecord[0].message.replace(/,/g, "\r\n"));
	} else {
		$("#message").val('充电报文不存在');
	}
	$("#Message").modal("show");
}
function messageSure(){
	$("#Message").modal("hide");
}
function pass(num){
//	nums = "846" + parseInt(num);
	nums = parseInt(num);
	window.parent.passVal(nums, "passValue", 'vehicle/vehicleInfo', 'drownDown3', '', 'carPage', 'vehicleInfo');
	search();
}
function chargingStationName(num){
	window.parent.detalisDrop('chargingStation/chargingStationDetail', num, $("#currentPage").val(), "drownDown1", "" ,"chargingStationPage" ,"chargingStation");
	$("#parentSkipMenu", parent.document).val("chargingStationPage");
	$("#detailID", parent.document).val(chargingRecord[num].chargingStationID);
}
//导出
function exportFile(type){
	showMessge("确定下载吗?", "model2");
	if(type == "equipment"){
		exportFlag = "equipment";
	} else if(type == "car"){
		exportFlag = "car";
	}
}
function sure(){
	showMessge("下载中......");
	if(exportFlag == "equipment"){
		var url = 'exportChargingProcess?subfolder=' + (chargingRecord[0] && chargingRecord[0].chargingStationID) +
		'&&fileName=' + (chargingRecord[0] && chargingRecord[0].chargingProcessFile) +
		'&&checkFlag=';
	} else if (exportFlag == "car"){
		var url = 'exportChargingProcess?subfolder=' + (chargingRecord[0] && chargingRecord[0].chargingStationID) +
		'&&fileName=' + (chargingRecord[0] && chargingRecord[0].carFile) +
		'&&checkFlag=';
	}
	$ajax(url, undefined, exportFileResult);
}
function exportFileResult(data){
	var result = data && data.result;
	if (result == "Success") {
		showLoading();
		var url = 'exportChargingProcess?subfolder=' + (chargingRecord[0] && chargingRecord[0].chargingStationID) +
		'&&fileName=' + (chargingRecord[0] && chargingRecord[0].chargingProcessFile) +
		'&&checkFlag=OK';
		downloadFile(url);
		showMessge("下载成功，过程文件正在生成！");
		setTimeout(hideLoading, 2000);
	} else if (result == "NotFound") {
		showMessge("下载失败，过程文件不存在!");
	} else {
		showMessge("下载失败，请重新下载 或 联系管理员！");
	}
}

function importFile(type) {
	if(type == "equipment"){
		exportFlag = "equipment";
	} else if(type == "car"){
		exportFlag = "car";
	}
	$("#importFileForm").empty();
	$("#importFileForm").append(
		'<div class="form-group" >'+
		'<label for="importFile" class="col-sm-3 control-label">充电过程文件</label>' + 
		'<div class="col-sm-8"><input id="importFile" name="importFile" type="file" class="form-control"/></div>' + 
		'</div>'
	);
	var option = {
		allowedFileExtensions: ['zip'],
		showUpload: false,
		previewFileIcon: '<img src="static/images/zip.png" style="width:80px;height:80px;" />',
		showErrorPreview: false
	};
	selectFile("importFile", option);
	$("#fileinputModal").modal("show");
}
function confirm() {
	var importFile = $("#importFile").val();
	if (!importFile) {
		$("#importFile").tips({
			side : 2,
			msg : '请选择要上传的充电过程文件',
			bg : '#AE81FF',
			time : 3
		});
		$("#importFile").focus();
	} else {
		var importFileName = importFile.substr(importFile.lastIndexOf("\\") + 1);
		var startChargingDTTM = timeStamp2String(chargingRecord[0].startChargingDTTM, 1);
		var fileLength = importFileName.length;
		if (fileLength > 18) {
			if (!((importFileName.substr(0, fileLength - 18).replace(",", "") == chargingRecord[0].equipmentID || 
					importFileName.substr(0, fileLength - 18).replace(",", "") == chargingRecord[0].equipmentNo || 
					importFileName.substr(0, fileLength - 18).replace(",", "") == chargingRecord[0].carNumber) && 
					importFileName.substr(fileLength - 18, 14) == startChargingDTTM)) {
				showMessge("上传文件错误，所选文件的车编号 或 桩号 或 开始充电时间与所需不符！");
				return;
			}
		} else {
			showMessge("上传文件名称错误，必须是'车自编号 或 桩号 + 开始充电时间'");
			return;
		}
		showLoading();
		$ajaxSubmit('importFileForm', 'importChargingProcess', importFileResult, {subfolder: chargingRecord[0] && chargingRecord[0].chargingStationID});
	}
}
function importFileResult(data) {
	setTimeout(hideLoading, 500);
	$("#fileinputModal").modal("hide");
	var result = data && data.result;
	if (result == "Success") {
		if(exportFlag == "equipment"){
			$('#chargingProcessFile').html('<img src="static/images/downloadFileCcs.png" style="width:40px;height:30px;" />' + formatFileSize(data && data.fileSize));
			$("#chargingProcessFile").attr("onclick","exportFile();return false;");
		} else if (exportFlag == "car"){
			$('#carFile').html('<img src="static/images/downloadFileBms.png" style="width:40px;height:30px;" />' + formatFileSize(data && data.fileSize));
			$("#carFile").attr("onclick","exportFile();return false;");
		}
		showMessge("上传成功！");
	} else if (result == "NotFound") {
		showMessge("上传失败，上传文件不存在！");
	} else if (result == "ChargingStationIDNotFound") {
		showMessge("上传失败，保存路径中的充电站ID不存在！");
	} else if (result == "NameError") {
		showMessge("上传失败，过程文件名称错误！");
	} else if (result == "Exists") {
		showMessge("上传失败，过程文件已存在！");
	} else {
		showMessge("上传异常，请重新选择文件 或 联系管理员！");
	}
}

function changeEchart(){
    var option = {
            tooltip : {
            	trigger: 'axis',
            	axisPointer:{
            		label: {
            			formatter: function (params) {
            				if (params && params.value) {
            					return timeStamp2String(new Date(params.value)).substr(11);
            				} else {
            					'时间异常';
            				}
            			}
            		}
            	}
            },
            legend: {
            	x: 'right',
                data:['充电电压','充电电流','充电SOC']
            },
            dataZoom: {
                show: true
            },
            xAxis: [
                {
                	type: 'time',
                	name: '充电时间',
                	min: (outputVoltageData && outputVoltageData[0] && outputVoltageData[0][0]) || '',
                	max: (outputVoltageData && outputVoltageData[outputVoltageData.length - 1] && outputVoltageData[outputVoltageData.length - 1][0]) || '',
                	splitNumber: (outputVoltageData && outputVoltageData.length && outputVoltageData.length) < 10 ? outputVoltageData && outputVoltageData.length : 10,
                	axisLabel: {
                		formatter : function (chargingTime) {
                			if(chargingTime){
                				return timeStamp2String(new Date(chargingTime)).substr(11);
                			} else {
                				return '';
                			}
                        }
                	}
                }
            ],
            yAxis: [
                {
                    type: 'value',
                    name: '充电电压',
                	min: 0,
                	max: 750,
                    position: 'left',
                    axisLine: {
                        lineStyle: {
                            color: '#01b2ac',
                        }
                    },
                    axisLabel: {
                        formatter: '{value}'
                    }
                },
                {
                    type: 'value',
                    name: '充电电流',
                    min: 0,
                    max: 750,
                    position: 'right',
                    axisLine: {
                        lineStyle: {
                            color: '#09be09',
                        }
                    },
                    axisLabel: {
                        formatter: '{value}'
                    }
                },
                {
                    type: 'value',
                    name: '充电SOC',
                    min: 0,
                    max: 100,
                    position: 'right',
                    show: false,
                    axisLine: {
                        lineStyle: {
                            color: '#fe902f',
                        }
                    },
                    axisLabel: {
                        formatter: '{value}'
                    }
                }
            ],
            series: [
                {
                    name:'充电电压',
                    type:'line',
                    symbol:'none',
                    itemStyle: {
                        normal : {
                            color: '#01b2ac',
                        }
                    },
                    data:outputVoltageData
                },
                {
                    name:'充电电流',
                    type:'line',
                    symbol:'none',
                    yAxisIndex:1,
                    itemStyle: {
                        normal : {
                            color: '#09be09',
                        }
                    },
                    data:outputElectricData
                },
                {
                    name:'充电SOC',
                    type:'line',
                    symbol:'none',
                    yAxisIndex:2,
                    itemStyle: {
                        normal : {
                            color: '#fe902f',
                        }
                    },
                    data:currentSOCData
                }
            ]
        };
    chargingChart.setOption(option);
}

function goback() {
	$("#detailID", parent.document).val("backFlag");
	window.parent.skipMenu('chargingEquipment/chargingRecord', 'drownDown4', '', 'chargingRecordPage', 'chargingRecord');
}